import path from "path";
import ts from "rollup-plugin-typescript2";
import replace from "@rollup/plugin-replace";
import json from "@rollup/plugin-json";
import rollupNodeResolve from "@rollup/plugin-node-resolve";
import rollupCommonjs from "@rollup/plugin-commonjs";
import rollupNodeBuiltins from "rollup-plugin-node-builtins";
import rollupNodeGlobals from "rollup-plugin-node-globals";
import pkg from "./package.json";
const resolve = (p) => path.resolve(__dirname, p);
const name = pkg.name;
const banner = `/* ${name} version ${pkg.version} */`;
const footer = `/* follow me on my web! www.bestlyg.com */`;
const packageOptions = { name: "BestlygDataStructures" };
const isProductionBuild = process.env.__PROD__ === "true";
const outputConfigs = {
  "esm-bundler": {
    file: resolve(`dist/src/${name}.esm-bundler.js`),
    format: `es`
  },
  "esm-browser": {
    file: resolve(`dist/src/${name}.esm-browser.js`),
    format: `es`
  },
  cjs: {
    file: resolve(`dist/src/${name}.cjs.js`),
    format: `cjs`
  },
  amd: {
    file: resolve(`dist/src/${name}.amd.js`),
    format: `amd`
  },
  umd: {
    file: resolve(`dist/src/${name}.umd.js`),
    format: `umd`
  },
  system: {
    file: resolve(`dist/src/${name}.system.js`),
    format: `system`
  },
  global: {
    file: resolve(`dist/src/${name}.global.js`),
    format: `iife`
  }
};
const packageFormats = [
  "esm-bundler",
  "cjs",
  "esm-browser",
  "global",
  "amd",
  "umd",
  "system"
];
const packageConfigs = packageFormats.map((format) =>
  createConfig(format, outputConfigs[format])
);
function createConfig(format, output, plugins = []) {
  if (!output) {
    console.log(require("chalk").yellow(`invalid format: "${format}"`));
    process.exit(1);
  }
  output.banner = banner;
  output.footer = footer;
  const isBundlerESMBuild = format === "esm-bundler";
  const isBrowserESMBuild = format === "esm-browser";
  const isNodeBuild = format === "cjs";
  const isGlobalBuild = format === "global";
  const isAmdBuild = format === "amd";
  const isUmdBuild = format === "umd";
  const isSystemBuild = format === "system";
  if (isGlobalBuild || isUmdBuild) {
    output.name = packageOptions.name;
    output.extend = true;
  }
  const tsPlugin = ts({
    check: true,
    tsconfig: path.resolve(__dirname, "tsconfig.json"),
    tsconfigOverride: {
      compilerOptions: {
        sourceMap: true,
        declaration: true,
        declarationMap: true
      }
    }
  });
  const entryFile = `src/index.ts`;
  const nodePlugins =
    format !== "cjs"
      ? [
          rollupNodeResolve({
            preferBuiltins: true
          }),
          rollupCommonjs({
            sourceMap: false
          }),
          rollupNodeBuiltins(),
          rollupNodeGlobals()
        ]
      : [];
  return {
    input: resolve(entryFile),
    plugins: [
      json({
        namedExports: false
      }),
      tsPlugin,
      createReplacePlugin(
        isBundlerESMBuild,
        isBrowserESMBuild,
        // isBrowserBuild?
        (isGlobalBuild || isBrowserESMBuild || isBundlerESMBuild) &&
          !packageOptions.enableNonBrowserBranches,
        isGlobalBuild,
        isNodeBuild,
        isAmdBuild,
        isUmdBuild,
        isSystemBuild
      ),
      ...nodePlugins,
      ...plugins
    ],
    output,
    onwarn: (msg, warn) => {
      if (!/Circular/.test(msg)) {
        warn(msg);
      }
    },
    treeshake: {
      moduleSideEffects: false
    }
  };
}
function createReplacePlugin(
  isBundlerESMBuild,
  isBrowserESMBuild,
  isBrowserBuild,
  isGlobalBuild,
  isNodeBuild,
  isAmdBuild,
  isUmdBuild,
  isSystemBuild
) {
  const replacements = {
    __VERSION__: `${pkg.version}`,
    NODE_ENV: isProductionBuild ? "production" : "development",
    __DEV__: !isProductionBuild,
    __PROD__: isProductionBuild,
    __BROWSER__: isBrowserBuild,
    __GLOBAL__: isGlobalBuild,
    __ESM_BUNDLER__: isBundlerESMBuild,
    __ESM_BROWSER__: isBrowserESMBuild,
    __AMD__: isAmdBuild,
    __UMD__: isUmdBuild,
    __SYSTEM__: isSystemBuild,
    __NODE_JS__: isNodeBuild
  };
  Object.keys(replacements).forEach((key) => {
    if (key in process.env) {
      replacements[key] = process.env[key];
    }
  });
  return replace(replacements);
}
function createMinifiedConfig(format) {
  const { terser } = require("rollup-plugin-terser");
  return createConfig(
    format,
    {
      file: outputConfigs[format].file.replace(/\.js$/, ".prod.js"),
      format: outputConfigs[format].format
    },
    [
      terser({
        module: /^esm/.test(format),
        compress: {
          ecma: 2015,
          pure_getters: true
        }
      })
    ]
  );
}
packageFormats.forEach((format) => {
  isProductionBuild && packageConfigs.push(createMinifiedConfig(format));
});
console.log(packageConfigs);
export default packageConfigs;
